# -*- coding: utf-8 -*-
#    Copyright 2005 Spike^ekipS <spikeekips@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from django.utils.httpwrappers import HttpResponse
from django.core.extensions import render_to_response
import simplejson, xmlrpclib, sqlobject

import http
from http.pageGetterBasic import get_page
from rss import parser_rss_or_html as parser
from model.channel import Channel as model_channel
from model.channel_user import ChannelUser as model_channel_user

import config

def validateUrl (request) :
	"""
	@retval,
		valid : validated url,
		not valid : exit status code, 404
	"""
	__argument = request.POST.copy()
	if not __argument.has_key("url") : return http.exitWithStatus(404)

	__r = http.validate_url(__argument["url"])
	if not __r :
		return http.exitWithStatus(404)
	else :
		return HttpResponse(__r)

def getRSSUrlCandidate (request) :
	__user = request.session.get("user", False)
	if not __user :
		return http.exitWithStatus(500)

	__argument = request.POST.copy()
	if not __argument.has_key("href") : return http.exitWithStatus(404)

	__url = http.validate_url(__argument["href"])
	if not __url :
		return http.exitWithStatus(500)

	# check whether this url is already add or not.
	# if already added, return 600 as status code.
	__server_add = xmlrpclib.Server("http://localhost:%d" % config.zzim_add_port)
	__id_channel = __server_add.isExist(__url)

	if __id_channel :
		__channel = model_channel.get(__id_channel)
		if __channel :
			__list = list(model_channel_user.select( \
				sqlobject.AND( \
					model_channel_user.q.userID == __user.id, \
					model_channel_user.q.channelID == __channel.id \
				) \
			))

			if len(__list) > 0 :
				return http.exitWithStatus(600)
			else :
				return render_to_response( \
					"channel/add_channel_result_channel.partial", \
					{
						"channel" : __channel, \
						"href" : __url, \
					}
				)

	__d = get_page(__url)
	if not __d.strip() :
		return http.exitWithStatus(500)

	__parsed = parser.parse(__d)

	if not __parsed.has_key("bozo") :
		return http.exitWithStatus(500)
	else :
		# If parser returns exception, we assumes this data is html or others, so
		# try to find rss links in this document by it's content-type.
		if not __parsed["bozo"] : # it's xml document.
			__is_podcasting = False
			if type(__parsed["namespaces"]) is dict and \
					__parsed["namespaces"].has_key("itunes"):
				# it's itunes podcasting feed.
				__is_podcasting = True

			return render_to_response( \
				"channel/add_channel_result_rss.partial", \
				{
					"parsed" : __parsed, \
					"is_podcasting" : __is_podcasting, \
					"href" : __url, \
				}
			)
		elif isinstance(__parsed["bozo_exception"], Exception) :
			__links = list()
			if __parsed.has_key("feed") and __parsed["feed"].has_key("links") :
				# it's html document, so try to find rss links in header.
				for i in __parsed["feed"]["links"] :
					__links.append(i)

			return render_to_response( \
				"channel/add_channel_result_links.partial", \
				{
					"links" : __links, \
					"href" : __url, \
				}
			)


__author__ =  "Spike^ekipS <spikeekips@gmail.com>"
__version__=  "0.1"
__nonsense__ = ""

__file__ = "views.py"


